<style lang="scss" scoped src="./update.scss"></style>
<template>
    <el-dialog
        custom-class="update-town-village-container"
        :title="id ? '编辑' : '新增'"
        :visible.sync="show"
        :close-on-click-modal="false"
        append-to-body
        @open="open"
        @closed="afterClose"
        center
        width="600px">
        <div class="regional-edit-container">
            <el-form ref="updateForm" label-position="right" :model="updateForm" :rules="updateFormRules" class="updateForm-steps2" label-width="120px">
                <el-form-item label="村名称" prop="name" v-if="name === 'RegionalUpdateVillage'">
                    <el-input v-model="updateForm.name" class="updateForm-steps2-input" placeholder="请输入村名称"></el-input>
                </el-form-item>
                <el-form-item label="镇名称" prop="cityCode" v-else>
                    <ask-city-cascader
                        v-if="!id"
                        :cityQuery="isOperation ? 'notAuth': 'authArea'"
                        ref="cityCascader"
                        v-model="updateForm.cityCode"
                        @change="handleChange"
                        :showModel="showModel"
                        clear />
                    <span v-else>{{updateForm.governmentName}}</span>
                </el-form-item>
                <el-form-item :label="isTown ? '镇管理员账号' : '村管理员账号'" prop="account">
                    <el-input v-model="updateForm.account" class="updateForm-steps2-input" placeholder="请输入登录账号"></el-input>
                </el-form-item>
                <el-form-item :label="isTown ? '镇管理员密码' : '村管理员密码'" prop="remind">
                    <el-form-item prop="password" v-if="updateType === 'add'">
                        <el-input v-model="updateForm.password" class="updateForm-steps2-input" placeholder="请输入账号密码"></el-input>
                    </el-form-item>
                    <template v-else>
                        <el-popover
                            placement="bottom"
                            width="300"
                            @show="showPop"
                            @after-leave="afterLeave"
                            trigger="click"
                            v-model="visiblePassword">
                            <el-form-item prop="newPassword" v-if="visiblePassword">
                                <div class="pop-box">
                                    <el-input v-model="updateForm.newPassword" class="updateForm-steps2-input" placeholder="请输入新密码" size="small"></el-input>
                                    <el-button @click="savePassword" size="small">确认</el-button>
                                </div>
                            </el-form-item>
                            <el-button type="text" slot="reference" :class="{reset: updateForm.password}">
                                {{updateForm.password ? "重置成功" : "重置密码"}}<i v-if="updateForm.password" class="el-icon-check"></i>
                            </el-button>
                        </el-popover>
                        <p class="tips">如密码无需修改可直接在下方点击完成</p>
                    </template>
                </el-form-item>
            </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancel" :disabled="loading">取消</el-button>
            <el-button type="primary" @click="toFinish('updateForm')" :loading="loading">完成</el-button>
        </div>
    </el-dialog>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { checkPassword } from "@/utils/vee-validate";
const customCheckPassword = (rule: any, value: any, callback: any) => {
    if (rule.field === "newPassword" && !value) {
        callback();
    } else if (!checkPassword(value)) {
        callback(new Error('请设置6~12位数字字母组合密码'));
    } else {
        callback();
    }
};

const checkTel = (rule: any, value: any, callback: any) => {
    if (!(/^[0-9a-zA-Z]*$/g.test(value))) {
        callback(new Error('请输入英文和数字'));
    } else {
        callback();
    }
};

@Component

export default class UpdateTownVillage extends Vue {
    show = false
    id = ""
    name = ""
    isOperation = false
    loading = false

    // 新增/编辑
    updateType = "add"
    // 表单
    updateForm: any = {
        governmentId: "",
        governmentName: "",
        cityCode: "",
        // 名称
        name: "",
        // 超管账号
        account: "",
        // 超管密码
        password: "",
        newPassword: ""
    }

    // 区域显示内容
    showModel: string[] = ['province', 'city', 'area', "town"] // 'town', 'village'

    // 级联选中的对象
    areaValue: any = {}
    // 是镇
    isTown = true

    // 修改密码显示
    visiblePassword = false

    updateFormRules = {
        cityCode: [
            { required: true, message: '请选择镇域', trigger: 'change' }
        ],
        name: [
            { required: true, message: '请输入村域名称', trigger: 'blur' }
        ],
        account: [
            { required: true, message: '请设置登陆账号', trigger: 'change' },
            { validator: checkTel, trigger: 'change' }
        ],
        remind: [
            { required: true, validator: (rule: any, value: any, callback: any) => { callback(); } }
        ],
        password: [
            { required: true, validator: customCheckPassword, trigger: 'change' }
        ],
        newPassword: [
            { required: true, validator: customCheckPassword, trigger: 'change' }
        ]
    }

    get getMenuName() {
        const _name = this.name;
        if (_name === "RegionalUpdateVillage") {
            return "MenuModuleManage";
        } else {
            return "MenuAreaManage";
        }
    }

    // 打开
    open() {
        this.updateType = this.id ? "edit" : "add";
        if (this.updateType === "edit") {
            this.initData();
        }
        this.isTown = this.name === "RegionalUpdateTown";
    }

    // 关闭
    close() {
        this.show = false;
    }

    // 关闭前
    afterClose() {
        (this.$refs.updateForm as any).resetFields();
        this.name = "";
        this.id = "";
    }

    // 初始化编辑内容
    initData() {
        this.$server["regional/getAccountInfo"]({
            data: {
                userId: this.id
            },
            loader: false
        }).then((res: any) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                this.updateForm = {
                    governmentId: data.governmentId,
                    governmentName: data.governmentName,
                    // cityCode
                    cityCode: data.cityCode || "",
                    name: data.governmentName.split("/").pop(),
                    // 超管账号
                    account: data.username,
                    // 超管密码
                    password: "",
                    newPassword: ""
                };
            } else {
                this.$message.error(res.data.message);
            }
        });
    }

    // 保存密码
    savePassword() {
        (this.$refs.updateForm as any).validateField("newPassword", (valid: any) => {
            if (!valid) {
                this.updateForm.password = this.updateForm.newPassword;
                this.visiblePassword = false;
            }
        });
    }

    // 关闭重置密码弹窗
    afterLeave() {
        this.updateForm.newPassword = "";
    }

    // 打开修改密码弹窗
    showPop() {
        this.updateForm.newPassword = this.updateForm.password;
    }

    // 完成
    toFinish(formName: string) {
        (this.$refs[formName] as any).validate((valid: any) => {
            if (valid) {
                const { governmentId, name, account, password } = this.updateForm;
                this.loading = true;
                this.$server["regional/updateTown"]({
                    data: {
                        governmentId: this.updateType === "edit" ? governmentId : this.isTown ? this.getAreaId() : "",
                        name,
                        orgCategoryId: this.isTown ? 6 : 8,
                        password,
                        userId: this.id || "",
                        userName: account
                    }
                }).then((res: any) => {
                    this.loading = false;
                    if (res.data.code === 200) {
                        if (this.id && password) {
                            this.toChangePassword(password);
                        } else {
                            this.$message({
                                type: 'success',
                                message: `${this.isTown ? '镇域' : '村域'}超管账号${this.id ? '已修改' : '开通成功'}!`
                            });
                            this.$emit("sure");
                        }
                    } else {
                        this.$message.error(res.data.message);
                    }
                }).catch(() => {
                    this.loading = false;
                });
            }
        });
    }

    // 修改密码
    toChangePassword(password: any) {
        this.$server["regional/updatePassword"]({
            data: {
                password,
                id: this.id || ""
            }
        }).then((res: any) => {
            if (res.data.code === 200) {
                this.$message({
                    type: 'success',
                    message: `${this.isTown ? '镇域' : '村域'}超管账号${this.id ? '已修改' : '开通成功'}!`
                });
                this.$emit("sure");
            } else {
                this.$message.error(res.data.message);
            }
        });
    }

    // 修改区域选择
    handleChange(val: any) {
        this.areaValue = val;
        if (!this.updateForm.cityCode) return false;
        if (val.province.code) {
            (this.$refs.updateForm as any).validateField("cityCode");
        }
    }

    // 查询政级id
    getAreaId() {
        let name = "";
        for (let i = this.showModel.length - 1; i >= 0; i--) {
            if (this.areaValue[this.showModel[i]].name === "") {
                continue;
            } else {
                name = `askCity${this.showModel[i]}PanelRef`;
                break;
            }
        }
        const list = (this.$refs.cityCascader as any).$refs[name][0].sourceList;
        return list.filter((item: any) => item.code.toString() === this.updateForm.cityCode)[0].id;
    }

    // 取消
    cancel() {
        this.show = false;
    }
}
</script>
